package com.bw.service.impl;

import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.exception.MyRuntimeException;
import com.bw.mapper.RoleMapper;
import com.bw.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: Wrj
 * @Date: 2025/3/9 10:07
 * @Description:
 **/
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<Role> list(Role role) {
        return roleMapper.list(role);
    }

    @Override
    public List<TbMenu> listMenu() {
        return roleMapper.listMenu();
    }

    @Override
    public Role listRole(String roleName) {
        return roleMapper.listRole(roleName);
    }

    @Override
    public List<Integer> listMenuIdsByRoleName(String roleName) {
        return roleMapper.listMenuIdsByRoleName(roleName);
    }

    @Transactional(rollbackFor = MyRuntimeException.class)
    @Override
    public Boolean add(Role role) {

        try {

            if (role.getRoleId()==null){
                roleMapper.add(role);

            }else {
                roleMapper.delete(role.getRoleId());
            }
            String menuIds = role.getMenuIds();
            String[] split = menuIds.split(",");
            for (int i = 0; i < split.length; i++) {
                roleMapper.addRoleMenu(role.getRoleId(),split[i]);
            }
            return true;

        }catch (MyRuntimeException e){
            e.printStackTrace();
            throw new MyRuntimeException("更新失败");
        }


    }


}
